package com.newworld.dmsapp2.register;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.serviceapply.WriteOutdoorPaperActivity;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.ui.view.choosecity.ChoosecityCharacterParser;
import com.newworld.dmsapp2.ui.view.choosecity.ChoosecityClearEditText;
import com.newworld.dmsapp2.ui.view.choosecity.ChoosecityPinyinComparator;
import com.newworld.dmsapp2.ui.view.choosecity.ChoosecitySideBar;
import com.newworld.dmsapp2.ui.view.choosecity.ChoosecitySideBar.OnTouchingLetterChangedListener;
import com.newworld.dmsapp2.ui.view.choosecity.ChoosecitySortAdapter;
import com.newworld.dmsapp2.ui.view.choosecity.ChoosecitySortModel;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

public class HouseChooseCommunityActivity extends BaseActivity implements
		OnClickListener {
	private ChoosecitySideBar sideBar;
	private ListView house_choose_list;
	private TextView dialog;
	private ChoosecitySortAdapter adapter;
	private ProgressBar getProjectDataProBar;
	/**
	 * 汉字转换成拼音的类
	 */
	private ChoosecityCharacterParser characterParser;
	private List<ChoosecitySortModel> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private ChoosecityPinyinComparator pinyinComparator;
	private ChoosecityClearEditText mClearEdit;
	
	private Intent intent;
	private String cityID = "";
	private List<Map<String, String>> requestList = new ArrayList<Map<String, String>>();
	private TextView titleBarTv;
	private LinearLayout leftLayout;
	private String sessionId;
	private boolean publicflag = WriteOutdoorPaperActivity.PUBLIC_FLAG;
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register_house_choose_list);
		initData();
		initViews();
		initEvents();
	}

	private void initData(){
		User user = SingleSample.getInstance(this).getUser();
		if(null != user){
			if(null != user.getSessionId() && !user.getSessionId().equals("")){
				sessionId = user.getSessionId();
			}
		}
	}
	@Override
	protected void initViews() {
		titleBarTv = (TextView) findViewById(R.id.titlebar_left_center_title);
		titleBarTv.setText("选择项目");
		leftLayout = (LinearLayout) findViewById(R.id.titlebar_left_left_layout);
		house_choose_list = (ListView) findViewById(R.id.house_choose_list);
		
		getProjectDataProBar = (ProgressBar) findViewById(R.id.proBar_get_data);
		intent = getIntent();
		if (intent != null) {
			cityID = intent.getStringExtra("cityID");
		}

		// 实例化汉字转拼音类
		characterParser = ChoosecityCharacterParser.getInstance();

		pinyinComparator = new ChoosecityPinyinComparator();

		sideBar = (ChoosecitySideBar) findViewById(R.id.choosehouse_sidrbar);
		dialog = (TextView) findViewById(R.id.choosehouse_dialog);
		sideBar.setTextView(dialog);
		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					house_choose_list.setSelection(position);
				}

			}
		});
		house_choose_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				String result = ((ChoosecitySortModel) adapter
						.getItem(position)).getName();
					Intent intent1 = new Intent();
				if(publicflag){
						
						String cityname = intent.getStringExtra("cityName").toString();
						Log.e("小区", cityname);
						intent1.putExtra("cityName", intent.getStringExtra("cityName").toString());
						intent1.putExtra("projectName", result);
						intent1.putExtra("projectID", ((ChoosecitySortModel) adapter
								.getItem(position)).getId());
						intent1.putExtra("repairphone", ((ChoosecitySortModel) adapter
								.getItem(position)).getRepairphone());
						Log.e("小区》phone", ((ChoosecitySortModel) adapter
								.getItem(position)).getRepairphone());
						intent1.setClass(HouseChooseCommunityActivity.this,
								HouseChooseReuseActivity.class);
						startActivityForResult(intent1, Config.REQUESTCODE_OUTDOOR_INTENT);
					
				}else{
					intent1.putExtra("projectName", result);
					intent1.putExtra("projectID", ((ChoosecitySortModel) adapter
							.getItem(position)).getId());
					setResult(Config.COMMUNITY_NORMAL, intent1);

					finish();
				}
				
				Toast.makeText(
						getApplication(),
						((ChoosecitySortModel) adapter.getItem(position))
								.getName(), Toast.LENGTH_SHORT).show();
			}
		});

		new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseChooseCommunityActivity.this)) {
					getProjectDataProBar
							.setVisibility(android.view.View.VISIBLE);
				} else {
					Toast.makeText(HouseChooseCommunityActivity.this,
							"请检查网络连接！", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseChooseCommunityActivity.this)) {
					try {
						String result = "";
						Map<String, String> map = new HashMap<String, String>();
						// 注册获取单元
						if (UserMessageActivity.INTENT_FLAG == 0 && !publicflag) {
							map.put("typeCode", Config.AREACODE_INDOOR+","+Config.AREACODE_BUSINESS);
							map.put("levelObjectId", cityID);
						}

						// 关联获取单元
						else if (UserMessageActivity.INTENT_FLAG == 1 && !publicflag) {
							map.put("typeCode", Config.AREACODE_INDOOR+","+Config.AREACODE_BUSINESS);
							map.put("levelObjectId", cityID);
						}
						//公区
						else if (publicflag) {
							map.put("typeCode", Config.AREACODE_OUTDOOR);
						}
						map.put("levelCode", "project");
					
						result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL, Config.GETHOUSE_NEW_URL),
								 map,sessionId);
						Log.e("公区》项目result", result);
						if (new JSONObject(result).getString("flag").equals(
								"success")) {
							String rows = new JSONObject(result)
							// inf->rows
									.getString("projectLevel");
							JSONArray jsonArray = new JSONArray(rows);
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jsonObject = jsonArray
										.getJSONObject(i);
								HashMap<String, String> projectMap = new HashMap<String, String>();
								@SuppressWarnings("unchecked")
								Iterator<String> iterator = jsonObject.keys();
								while (iterator.hasNext()) {
									String key = iterator.next();
									String value = jsonObject.get(key) + "";
									projectMap.put(key, value);
								}

								requestList.add(projectMap);

							}

						} else {
							Toast.makeText(HouseChooseCommunityActivity.this,
									"获取数据失败！", Toast.LENGTH_SHORT).show();
						}

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				getProjectDataProBar.setVisibility(View.INVISIBLE);
				SourceDateList = filledData(requestList);
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);
				adapter = new ChoosecitySortAdapter(
						HouseChooseCommunityActivity.this, SourceDateList);
				house_choose_list.setAdapter(adapter);
			}
		}.execute(null, null, null);
		mClearEdit = (ChoosecityClearEditText) findViewById(R.id.choosehouse_filter_edit);

		// 根据输入框输入值的改变来过滤搜索
		mClearEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private List<ChoosecitySortModel> filledData(List<Map<String, String>> list) {
		List<ChoosecitySortModel> mSortList = new ArrayList<ChoosecitySortModel>();

		for (int i = 0; i < list.size(); i++) {
			ChoosecitySortModel sortModel = new ChoosecitySortModel();
			sortModel.setName((String) list.get(i).get("projectName"));
			sortModel.setId((String) list.get(i).get("id"));
			sortModel.setRepairphone((String) list.get(i).get("repairphone"));
			// 汉字转换成拼音
			String pinyin = characterParser.getSelling((String) list.get(i)
					.get("projectName"));
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}

			mSortList.add(sortModel);
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<ChoosecitySortModel> filterDateList = new ArrayList<ChoosecitySortModel>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
		} else {
			filterDateList.clear();
			for (ChoosecitySortModel sortModel : SourceDateList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

	@Override
	protected void initEvents() {

		// 添加点击
		leftLayout.setOnClickListener(this);
	}

	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			Intent intent = new Intent();
			intent.putExtra("houseFullName", "");
			intent.putExtra("houseID", "");
			if(publicflag){
				setResult(Config.RESULTCODE_OUTDOOR_INTENT, intent);
				finish();
			}else{
				//setResult(Activity.RESULT_OK, intent);
				finish();
			}
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.titlebar_left_left_layout:
			finish();
			break;
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		   // TODO Auto-generated method stub
		   super.onActivityResult(requestCode, resultCode, data);
		   if(requestCode == Config.REQUESTCODE_OUTDOOR_INTENT && resultCode == Config.RESULTCODE_OUTDOOR_INTENT){
				if (data != null) {
					if(null != data.getExtras().getString("houseId")){
						Log.e("小区houseid",data.getExtras().getString("houseId"));
					}else{
						Log.e("小区houseid","houseid为空");
					}
					this.setResult(Config.RESULTCODE_OUTDOOR_INTENT,data);
				}else{
					this.setResult(Config.RESULTCODE_OUTDOOR_INTENT);
				}
			    this.finish();
			   }
		}
}
